package cn.stylefeng.guns.modular.business.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import cn.stylefeng.guns.modular.business.comment.YunHeKey;
import cn.stylefeng.guns.modular.business.entity.RiverManagement;
import cn.stylefeng.guns.modular.business.enums.RiverDevelopmentExceptionEnum;
import cn.stylefeng.guns.modular.business.enums.RiverManagementExceptionEnum;
import cn.stylefeng.guns.modular.business.mapper.RiverManagementMapper;
import cn.stylefeng.guns.modular.business.pojo.RiverManagementRequest;
import cn.stylefeng.guns.modular.business.service.RiverManagementService;
import cn.stylefeng.guns.modular.business.service.SubUseBrowseService;
import cn.stylefeng.roses.kernel.auth.api.LoginUserApi;
import cn.stylefeng.roses.kernel.auth.api.pojo.login.LoginUser;
import cn.stylefeng.roses.kernel.db.api.factory.PageFactory;
import cn.stylefeng.roses.kernel.db.api.factory.PageResultFactory;
import cn.stylefeng.roses.kernel.db.api.pojo.page.PageResult;
import cn.stylefeng.roses.kernel.rule.exception.base.ServiceException;
import cn.stylefeng.roses.kernel.rule.util.HttpServletUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 河道管理业务实现层
 *
 * @author zhangyaowen
 * @date 2021/10/08 16:51
 */
@Service
public class RiverManagementServiceImpl extends ServiceImpl<RiverManagementMapper, RiverManagement> implements RiverManagementService {

    @Resource
    private LoginUserApi loginUserApi;
    @Resource
    private SubUseBrowseService subUseBrowseService;

	@Override
    public void add(RiverManagementRequest riverManagementRequest) {
        RiverManagement riverManagement = new RiverManagement();
        BeanUtil.copyProperties(riverManagementRequest, riverManagement);
        this.save(riverManagement);
    }

    @Override
    public void del(RiverManagementRequest riverManagementRequest) {
        RiverManagement riverManagement = this.queryRiverManagement(riverManagementRequest);
        this.removeById(riverManagement.getId());
    }

    @Override
    public void edit(RiverManagementRequest riverManagementRequest) {
        RiverManagement riverManagement = this.queryRiverManagement(riverManagementRequest);
        BeanUtil.copyProperties(riverManagementRequest, riverManagement);
        this.updateById(riverManagement);
    }

    @Override
    public RiverManagement detail(RiverManagementRequest riverManagementRequest) {
        return this.queryRiverManagement(riverManagementRequest);
    }

    @Override
    public PageResult<Map<String,Object>> findPage(RiverManagementRequest riverManagementRequest) {
        LambdaQueryWrapper<RiverManagement> queryWrapper = new LambdaQueryWrapper<>();

        String riverName = riverManagementRequest.getRiverName();
        queryWrapper.like(ObjectUtil.isNotEmpty(riverName), RiverManagement::getRiverName, riverName);
        Page<RiverManagement> sysRolePage = this.page(PageFactory.defaultPage(), queryWrapper);

        PageResult<RiverManagement> riverManagementPageResult = PageResultFactory.createPageResult(sysRolePage);
        PageResult<Map<String,Object>> pageResult = new PageResult<>();
        List<RiverManagement> riverManagementList = riverManagementPageResult.getRows();
        List<Map<String,Object>> mapList=new ArrayList<>();
        for(RiverManagement riverManagement :riverManagementList){
            Map<String, Object> map = new HashMap<String, Object>();
            byte[] key = YunHeKey.PASSWORD.getBytes(StandardCharsets.UTF_8);
            SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);

            String jmid = YunHeKey.HDGL+riverManagement.getId();
            String encryptHex = aes.encryptHex(jmid);
            map.put("id",encryptHex);
            map.put("title",riverManagement.getRmTitle());
            map.put("rhdAnnalsfrom",riverManagement.getRhdAnnalsfrom());
            mapList.add(map);

        }
        pageResult.setRows(mapList);
        pageResult.setPageSize(riverManagementPageResult.getPageSize());
        pageResult.setPageNo(riverManagementPageResult.getPageNo());
        pageResult.setTotalPage(riverManagementPageResult.getTotalPage());
        pageResult.setTotalRows(riverManagementPageResult.getTotalRows());
        return pageResult;
    }

    @Override
    public List<Map<String, Object>> toReview(String jmid) {
        byte[] key =YunHeKey.PASSWORD.getBytes(StandardCharsets.UTF_8);
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);
        String decryptStr = aes.decryptStr(jmid, CharsetUtil.CHARSET_UTF_8);
        //获取ID字符串YHSJ后面真实的的id
        String id = StrUtil.subAfter(decryptStr,YunHeKey.HDGL,false);
        HttpServletRequest request = HttpServletUtil.getRequest();
        Long userid;
        if (ObjectUtil.isNotNull(request)) {

            LoginUser loginUser = loginUserApi.getLoginUser();
            userid = loginUser.getUserId();
        } else {
            throw new ServiceException(RiverDevelopmentExceptionEnum.REQUEST_EMPTY);
        }
        LambdaQueryWrapper<RiverManagement> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(ObjectUtil.isNotEmpty(id), RiverManagement::getId, id);
        List<RiverManagement> riverManagementList = this.list(queryWrapper);
        if(userid != 0l && userid != -1l) {
            subUseBrowseService.saveBrowse(YunHeKey.HEDAO,riverManagementList.get(0).getRmTitle(),userid,request);
        }
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (RiverManagement riverManagement : riverManagementList) {

            Map<String, Object> map = new HashMap<String, Object>();
            map = JSONObject.parseObject(JSONObject.toJSONString(riverManagement), Map.class);

            // 获取类的属性
            Field[] declaredFields = RiverManagement.class.getDeclaredFields();
            List<Map<String, Object>> mplist = new ArrayList<>();
            // 遍历属性，获取属性上ApiModelProperty的值，属性的名，存入Properties
            if (declaredFields.length != 0) {

                int i = 1;
                Map<String, Object> p = new HashMap<String, Object>();
                for (Field field : declaredFields) {

                    Map<String, Object> mp = new HashMap<String, Object>();
                    if (field.getAnnotation(ApiModelProperty.class) != null) {
                        //获取注解属性
                        ApiModelProperty aa = field.getAnnotation(ApiModelProperty.class);
                        // key和value可根据需求存
                        // 这存的key为注解的值，value为类属性名
                        if ("rmTitle".equals(field.getName()) || "riverManagement".equals(field.getName())) {
                            if ("rmTitle".equals(field.getName()) ) { //标题
                                p.put("title", map.get(field.getName()));
                            }else {
                                p.put(field.getName(), map.get(field.getName()));
                            }
                        }else{
                            mp.put("key", aa.value());
                            mp.put("value", map.get(field.getName()));

                            if (i != 1) {
                                mplist.add(mp);
                            }
                        }
                    }
                    i++;
                }
                p.put("list", mplist);
                if (i != 1) {
                    mapList.add(p);
                }
            }
        }
        return mapList;
    }

    @Override
    public List<RiverManagement> findList(RiverManagementRequest riverManagementRequest) {
        LambdaQueryWrapper<RiverManagement> wrapper = this.createWrapper(riverManagementRequest);
        return this.list(wrapper);
    }

    /**
     * 获取信息
     *
     * @author zhangyaowen
     * @date 2021/10/08 16:51
     */
    private RiverManagement queryRiverManagement(RiverManagementRequest riverManagementRequest) {
        RiverManagement riverManagement = this.getById(riverManagementRequest.getId());
        if (ObjectUtil.isEmpty(riverManagement)) {
            throw new ServiceException(RiverManagementExceptionEnum.RIVERMANAGEMENT_NOT_EXISTED);
        }
        return riverManagement;
    }

    /**
     * 创建查询wrapper
     *
     * @author zhangyaowen
     * @date 2021/10/08 16:51
     */
    private LambdaQueryWrapper<RiverManagement> createWrapper(RiverManagementRequest riverManagementRequest) {
        LambdaQueryWrapper<RiverManagement> queryWrapper = new LambdaQueryWrapper<>();

        Long id = riverManagementRequest.getId();
        String riverName = riverManagementRequest.getRiverName();
        String rtFirst = riverManagementRequest.getRtFirst();
        String rtSecond = riverManagementRequest.getRtSecond();
        String rtThrid = riverManagementRequest.getRtThrid();
        String historyDating = riverManagementRequest.getHistoryDating();
        String theCommon = riverManagementRequest.getTheCommon();
        String riverManagement = riverManagementRequest.getRiverManagement();
        String quoteAnnotation = riverManagementRequest.getQuoteAnnotation();
        String rhdAnnalsfrom = riverManagementRequest.getRhdAnnalsfrom();
        String rhdAnnalspage = riverManagementRequest.getRhdAnnalspage();

        queryWrapper.eq(ObjectUtil.isNotNull(id), RiverManagement::getId, id);
        queryWrapper.like(ObjectUtil.isNotEmpty(riverName), RiverManagement::getRiverName, riverName);
        queryWrapper.like(ObjectUtil.isNotEmpty(rtFirst), RiverManagement::getRtFirst, rtFirst);
        queryWrapper.like(ObjectUtil.isNotEmpty(rtSecond), RiverManagement::getRtSecond, rtSecond);
        queryWrapper.like(ObjectUtil.isNotEmpty(rtThrid), RiverManagement::getRtThrid, rtThrid);
        queryWrapper.like(ObjectUtil.isNotEmpty(historyDating), RiverManagement::getHistoryDating, historyDating);
        queryWrapper.like(ObjectUtil.isNotEmpty(theCommon), RiverManagement::getTheCommon, theCommon);
        queryWrapper.like(ObjectUtil.isNotEmpty(riverManagement), RiverManagement::getRiverManagement, riverManagement);
        queryWrapper.like(ObjectUtil.isNotEmpty(quoteAnnotation), RiverManagement::getQuoteAnnotation, quoteAnnotation);
        queryWrapper.like(ObjectUtil.isNotEmpty(rhdAnnalsfrom), RiverManagement::getRhdAnnalsfrom, rhdAnnalsfrom);
        queryWrapper.like(ObjectUtil.isNotEmpty(rhdAnnalspage), RiverManagement::getRhdAnnalspage, rhdAnnalspage);

        return queryWrapper;
    }

}